package yz.mr.FiltrationText3;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class FiltrationText3Reduce extends Reducer<Text,Student, NullWritable,Student> {
    @Override
    protected void reduce(Text key, Iterable<Student> values, Reducer<Text, Student, NullWritable, Student>.Context context) throws IOException, InterruptedException {
        //创建学生列表
        ArrayList<Student> students = new ArrayList<>();
        for (Student student : values) {
            //1500100001	施笑槐,22,女,文科六班,406

            //每次添加数据时，都是对象的引用添加到列表中，所以当前对象数据发生变化时，students都指向同一个对象
            Student student1 = new Student(student.getId(),student.getName(),student.getAge(),student.getSex(),student.getClazz(),student.getScore());
            students.add(student1);
        }
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                                //这种默认的是升序，所以我们就要改成降序  这里就是取反
                if (o1.score>o2.score){
                    return -1;  //升序的话是返回1 ，降序返回-1
                }
                else if (o1.score == o2.score){
                    return 0;
                }
                else {
                    return 1;
                }
            }
        });
        Student student01 = students.get(0);
        context.write(NullWritable.get(), student01); //如果改完之后就可以用Student
        Student student02 = students.get(1);
        context.write(NullWritable.get(), student02);
        Student student03 = students.get(2);
        context.write(NullWritable.get(), student03);
    }
}
